import React, { useRef, useState } from 'react';
import { Button, message, Form, Input, Radio, Spin, TreeSelect, InputNumber, Divider } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PlusOutlined, FormOutlined } from '@ant-design/icons';
import { add, edit, update, getPidList } from '@/services/blogAdmin/article/articleType/api';
import CUpload from '@/components/common/CUpload/index';
interface PorpsType {
  onConfirm: () => void;
  id?: number;
  pid?: number;
  disabled?: boolean;
}
const FormIndex: React.FC<PorpsType> = (porps) => {
  const restFormRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(porps.id ? false : true);
  const [pidList, setPidList] = useState<any>([]);
  const [pidListLoading, setPidListLoading] = useState<boolean>(false);
  const { TextArea } = Input;
  const formData: API.BlogAdminArticleTypeForm = {
    id: null,
    name: '',
    type: 1,
    status: 1,
    level: 1,
    pid: 0,
    sort: 1,
    image_id: null,
    description: '',
    open_type: 0,
    attribute: 0,
    external_link: '',
    seo_title: '',
    seo_keyword: '',
    seo_description: '',
  };
  return (
    <DrawerForm<API.BlogAdminArticleTypeForm>
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      formRef={restFormRef}
      initialValues={formData}
      title={porps.id ? '编辑' : '添加'}
      autoFocusFirstInput
      isKeyPressSubmit
      trigger={
        porps.id ? (
          <Button type="primary" disabled={porps.disabled ? true : false} size="small">
            <FormOutlined />
            编辑
          </Button>
        ) : porps.pid ? (
          <Button type="primary" size="small">
            <PlusOutlined />
            添加子分类
          </Button>
        ) : (
          <Button type="primary">
            <PlusOutlined />
            添加
          </Button>
        )
      }
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              loading={loading ? false : true}
              key="extra-reset"
              onClick={async () => {
                const id = props.form?.getFieldValue('id');
                if (id) {
                  await setLoading(false);
                  const res = await edit(id);
                  if (res.status === 20000) {
                    restFormRef.current?.setFieldsValue(res.data);
                    await setLoading(true);
                  }
                } else {
                  props.reset();
                }
              }}
            >
              重置
            </Button>,
          ];
        },
      }}
      onFinish={async (values: any) => {
        if (!Number.isInteger(values.image_id)) {
          values.image_id = values.image_id && values.image_id[0].id;
        }
        if (!values.image_id) {
          values.image_id = null;
        }
        let res: any = {};
        if (porps.id) {
          res = await update(porps.id, values);
        } else {
          res = await add(values);
        }
        if (res.status === 20000) {
          message.success(res.message);
          porps.onConfirm();
          return true;
        }
        return false;
      }}
      onVisibleChange={async (visible) => {
        if (visible) {
          if (porps.pid) {
            await restFormRef.current?.setFieldsValue({ pid: porps.pid });
          }
          if (porps.id) {
            await setLoading(false);
            const res = await edit(porps.id);
            if (res.status === 20000) {
              await restFormRef.current?.setFieldsValue(res.data);
              await setLoading(true);
            }
          }
          const data: { id?: number } = {};
          if (porps.id) {
            data.id = porps.id;
          }
          await setPidListLoading(true);
          const pidRes = await getPidList(data);
          if (pidRes.status == 20000) {
            await setPidListLoading(false);
            await setPidList(pidRes.data);
          }
        }
      }}
    >
      <Spin spinning={loading ? false : true}>
        {loading && (
          <>
            <Form.Item
              label="父级分类"
              name="pid"
              rules={[{ required: true, message: '请选择父级分类' }]}
            >
              <TreeSelect
                treeData={pidList}
                allowClear
                placeholder="请选择父级分类"
                loading={pidListLoading}
              />
            </Form.Item>
            <Form.Item
              label="分类名称"
              name="name"
              rules={[{ required: true, message: '请输入分类名称' }]}
            >
              <Input maxLength={100} allowClear placeholder="请输入分类名称" />
            </Form.Item>
            <Form.Item name="image_id" label="分类图片">
              <CUpload
                key="image_id"
                imageList={
                  restFormRef.current?.getFieldValue('image_to')
                    ? [restFormRef.current.getFieldValue('image_to')]
                    : []
                }
                onChange={(data: any) => {
                  if (!data.length) {
                    restFormRef.current?.setFieldsValue({ image_id: null });
                  }
                }}
              />
            </Form.Item>
            <Form.Item label="分类描述" name="description">
              <TextArea showCount maxLength={100} placeholder="请输入分类描述" />
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Radio.Group name="status">
                <Radio value={0}>隐藏</Radio>
                <Radio value={1}>显示</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="type"
              label="分类类型"
              rules={[{ required: true, message: '请选择分类类型' }]}
            >
              <Radio.Group name="type">
                <Radio value={1}>文字列表</Radio>
                <Radio value={2}>图片列表</Radio>
                <Radio value={3}>下载列表</Radio>
                <Radio value={4}>咨询列表</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              name="open_type"
              label="打开方式"
              rules={[{ required: true, message: '请选择打开方式' }]}
            >
              <Radio.Group name="open_type">
                <Radio value={0}>原页面打开</Radio>
                <Radio value={1}>新页面打开</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="attribute"
              label="栏目属性"
              rules={[{ required: true, message: '请选择栏目属性' }]}
            >
              <Radio.Group name="attribute">
                <Radio value={0}>列表菜单</Radio>
                <Radio value={1}>单页菜单</Radio>
                <Radio value={2}>外链菜单</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label="外链网址" name="external_link">
              <TextArea showCount maxLength={100} placeholder="请输入外链网址" />
            </Form.Item>
            <Form.Item label="排序" name="sort" rules={[{ required: true, message: '请输入排序' }]}>
              <InputNumber
                maxLength={11}
                placeholder="请输入排序"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
            <Divider orientation="left">SEO配置</Divider>
            <Form.Item label="Title" name="seo_title">
              <Input maxLength={100} allowClear placeholder="请输入Title" />
            </Form.Item>

            <Form.Item label="Meta Keywords" name="seo_keyword">
              <TextArea showCount maxLength={100} placeholder="请输入Meta Keywords" />
            </Form.Item>
            <Form.Item label="Meta Description" name="seo_description">
              <TextArea showCount maxLength={100} placeholder="请输入Meta Description" />
            </Form.Item>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default FormIndex;
